package com.mybatis;

import com.mybatis.entity.Book;
import com.mybatis.mapper.BookMapper;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * @author qinjiasheng
 */
public class SqlSessionFactoryTest {
	public static void main(String[] args) {
		String resource = "mybatis-config.xml";
		SqlSession sqlSession = null;
		try {
			InputStream inputStream = Resources.getResourceAsStream(resource);
			SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
			sqlSession = sqlSessionFactory.openSession();
			BookMapper bookMapper = sqlSession.getMapper(BookMapper.class);
			Book book1 = new Book("Hello,world1","hello Kity1",19.9f);
			bookMapper.insertBook(book1);
			Book book2 = new Book("Hello,world2","hello Kity2",29.9f);
			bookMapper.insertBook(book2);
			Book book3 = new Book("Hello,world3","hello Kity3",39.9f);
			bookMapper.insertBook(book3);
			Book book4 = new Book("Hello,world3", "hello Kity8", 39.9f);
			bookMapper.updateBook(book4);
			List<Book> _books = bookMapper.getBook();
			for (Book book : _books) {
				System.out.println("book = [" + book + "]");
			}
			sqlSession.commit();
		} catch (IOException e) {
			sqlSession.rollback();
		}finally {
			if (sqlSession != null) {
				sqlSession.close();
			}
		}
	}
}
